package org.xxpay.pay.channel.quanming;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;

import org.springframework.stereotype.Service;
import org.xxpay.common.http.HttpRequestTemplate;

import org.xxpay.common.util.sign.SignUtils;

import org.xxpay.common.util.str.StringUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;

import java.util.Map;

@Service
public class QuanminPaymentService extends BasePayment {
    private final static String logPrefix = "【全民供码】";
    @Override
    public String getChannelName() {
        return  QuanminConfig.CHANNEL_NAME;
    }

    @Override
    public JSONObject pay(PayOrder payOrder){

//        String channelId = payOrder.getChannelId();
//        JSONObject retObj;
//        switch (channelId) {
//            case QuanminConfig.CHANNEL_NAME_WX_QR:
//                retObj = doOrderReq(payOrder,"wxwap");
//                break;
//            case QuanminConfig.CHANNEL_NAME_ALI_QR:
//                retObj = doOrderReq(payOrder, "zfbwap");
//                break;
//            case QuanminConfig.CHANNEL_NAME_ysf:
//                retObj = doOrderReq(payOrder, "ysf");
//                break;
//                default:
//                    retObj = buildRetObj(PayConstant.RETURN_VALUE_FAIL, "不支持的渠道[channelId="+channelId+"]");
//                    break;
//        }
        return doOrderReq(payOrder);
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject query(PayOrder payOrder) {
        QuanminConfig config = new QuanminConfig(getPayParam(payOrder));
        String payOrderId = payOrder.getPayOrderId();
        _log.info("{}开始查询通道订单,payOrderId={}", logPrefix, payOrderId);
        Map<String, Object> params = Maps.newHashMap();
        params.put("merId", config.getAppId());
        params.put("orderId", payOrder.getPayOrderId());
        params.put("nonceStr", payOrder.getPayOrderId());
        params.put("sign", getSign(params, config));
        _log.info("{}订单查询请求数据:{}", getChannelName(), JSON.toJSONString(params));
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(config.getRequestUrl()+QuanminConfig.REQ_PAY_QUERY_URL_FIXX, params, JSONObject.class);
        _log.info("{}响应数据:{}", getChannelName(), JSON.toJSONString(origin));
        // 响应对象
        JSONObject retObj = new JSONObject();
        if(StringUtils.equals(origin.getString("code"), "1")) {
            int status = 1;
            JSONObject data = JSONObject.parseObject(origin.getString("data"));
            if(StringUtils.equals(data.getString("status "),"1")){
                status = 2;
            }
            retObj.put("status",status);
            retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_SUCCESS);
            retObj.put("channelOrderNo", origin.getString("orderId"));
            retObj.put("channelObj", origin);
            return retObj;
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.getString("msg"));
        return retObj;
    }
    //下单具体实现
    private JSONObject doOrderReq(PayOrder payOrder) {
        QuanminConfig config = new QuanminConfig(getPayParam(payOrder));
        //请求参数
        Map<String,Object> params = Maps.newHashMap();
        setParams(payOrder,config,params);
        _log.info("{}请求数据:{}", getChannelName(), JSON.toJSONString(params));
        // 将订单改为支付中
        rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(config.getRequestUrl()+QuanminConfig.REQ_PAY_URL_FIXX, params, JSONObject.class);
        _log.info("{}响应数据:{}", logPrefix, origin.toJSONString());
        // 响应对象
        JSONObject retObj = new JSONObject();
        if(StringUtils.equals(origin.getString("code"),"1")){
            JSONObject data = JSONObject.parseObject(origin.getString("data"));
            return buildPayResultOfForm(retObj, payOrder,"<script type=\"text/javascript\">\n" +
                    "　　window.location.href=\""+ data.getString("payurl")+"\";\n" +
                    "　　</script>" );
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.toJSONString());
        return retObj;
    }


    //设置请求参数
    private void setParams(PayOrder payOrder, QuanminConfig config ,Map<String,Object> params){
        params.put("merId", config.getAppId());
        params.put("orderId", payOrder.getPayOrderId());
        params.put("orderAmt", AmountUtil.convertCent2Dollar(String.valueOf(payOrder.getAmount())));
        params.put("channel", config.getPayMode());
        params.put("desc", payOrder.getPayOrderId());
        params.put("ip", payOrder.getClientIp());
        params.put("notifyUrl", payConfig.getNotifyUrl(getChannelName()));
        params.put("returnUrl", payOrder.getReturnUrl());
        params.put("nonceStr", payOrder.getPayOrderId());
        params.put("sign",getSign(params,config));
    }

    //获取sign
    private String getSign(Map<String,Object> params,QuanminConfig config){
        String signTxt = SignUtils.parameterText(params);
        _log.info("{}加密前字符串：{}", logPrefix, signTxt+"&key="+config.getPrivateStorePathPwd());
        String signValue = SignUtils.MD5.createSign(signTxt, "&key="+config.getPrivateStorePathPwd(), SignUtils.CHARSET_UTF8).toUpperCase();
        _log.info("{}签名前字符串：{}", logPrefix, signValue);
        String sign = SignUtils.RSA2.createSign(signValue, config.getPrivateKey(), SignUtils.CHARSET_UTF8);
        _log.info("{}签名后Sign值：{}", logPrefix, sign);
        return sign;
    }
}
